#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    QStringList items;
    items.append("LocalHost");
    items.append("Broadcast");
    items.append("Manual");
    ui->addressType->addItems(items);
    ui->addressType->setCurrentIndex(-1);
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::on_addressType_currentTextChanged(const QString &text)
{
    if(text == "LocalHost")
        ui->address->setText("127.0.0.1");
    else if(text == "Broadcast")
        ui->address->setText("255.255.255.255");
    else
    {
        ui->address->clear();
        ui->address->setFocus();
    }
}

void Dialog::on_btn_sendCmd_clicked()
{
    QString address=ui->address->text().trimmed();
    QString portStr=ui->port->text().trimmed();
    if(address.isEmpty() || portStr.isEmpty())
        return;

    int port=portStr.toInt();
    QString cmd=ui->cmd->text();
    if(cmd.isEmpty())
        return;

    sp_sendData(cmd.toUtf8(),address,port);
    ui->cmd->clear();
    QMessageBox::information(this,"操作已完成","指令已发送");
}

void Dialog::on_btn_sendMsg_clicked()
{
    QString address=ui->address->text().trimmed();
    QString portStr=ui->port->text().trimmed();
    if(address.isEmpty() || portStr.isEmpty())
        return;
    int port=portStr.toInt();

    QString action=ui->action->text().trimmed();
    QString extra=ui->extra->text().trimmed();
    if(action.isEmpty() || extra.isEmpty())
        return;

    QJsonObject obj;
    obj.insert("action",action);
    obj.insert("extra",extra);

    sp_sendData(QJsonDocument(obj).toJson(),address,port);
    ui->action->clear();
    ui->extra->clear();
    QMessageBox::information(this,"操作已完成","消息已发送");
}
